package com.summer.data.connection.source;

import com.summer.data.connection.SessionFactory;
import com.summer.data.dialect.Dialect;

import javax.sql.DataSource;
import java.sql.Connection;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 345480567@qq.com
 */
public class DataSourceNameSessionFactory extends AbstractSessionFactory implements SessionFactory {

    private static final Map<String, DataSource> DIALECT_MAP = new HashMap<String, DataSource>();

    public static void regDataSource(String name, DataSource dataSource) {
        assert name != null;
        assert dataSource != null;
        DIALECT_MAP.put(name, dataSource);
    }

    private String dataSourceName;

    private DataSourceSessionFactory dataSourceSessionFactory;

    public DataSourceNameSessionFactory(String dataSourceName, Dialect dialect) {
        super(null);
        this.dataSourceName = dataSourceName;
        initDialect();
    }

    public DataSourceNameSessionFactory(Dialect dialect) {
        super(dialect);
        initDialect();
    }

    @Override
    public Connection getConnection() {
        if (dataSourceSessionFactory == null) {
            dataSourceSessionFactory = new DataSourceSessionFactory(DIALECT_MAP.get(dataSourceName), getDialect());
        }
        return dataSourceSessionFactory.getConnection();
    }

}
